package activity.Left;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hichip.callback.PlayLocalFileCallback;
import com.hichip.campro.R;
import com.hichip.sdk.PlayLocal;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.TimeZone;

import activity.FishEye.FishEyePlaybackLocalActivity;
import activity.Left.adapter.StickyGridVideoAdapter;
import activity.WallMounted.WallMountedPlayLocalActivity;
import activity.video.PlaybackLocalActivity;
import activity.video.VideoActivity;
import activity.video.adapter.VideoInfoAdapter;
import base.HiFragment;
import bean.LeftLocalFileBean;
import bean.MyCamera;
import bean.VideoInfo;
import butterknife.BindView;
import butterknife.ButterKnife;
import common.HiDataValue;
import custom.dialog.NiftyDialogBuilder;
import custom.stickygridview.GridItem;
import custom.stickygridview.YMComparator;
import utils.HiToast;
import utils.HiTools;
import utils.SharePreUtils;

//本地文件  录像的Tab
public class LeftLocalVideoFragment extends HiFragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, PlayLocalFileCallback {
    private MyCamera mMyCamera;
    public ArrayList<GridItem> mGirdList = new ArrayList<>();
    private Map<String, Integer> sectionMap = new HashMap<String, Integer>();
    private static int section = 1;
    @BindView(R.id.sticky_gridview) GridView sticky_gridview;
    public StickyGridVideoAdapter mAdapter;
    public List<GridItem> mDeleteList = new ArrayList<GridItem>();
    public static final String FILE_PATH = "file_path";

    private String absolutePath;
    protected File mConverFile;
    private PlayLocal mPlayLocal;
    private long mFirstTime = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_left_local_video, null);
        ButterKnife.bind(this, view);
        initViewAndData(view);
        setListeners();
        return view;
    }

    private void setListeners() {
        sticky_gridview.setOnItemClickListener(this);
        sticky_gridview.setOnItemLongClickListener(this);
    }

    private void initViewAndData(View view) {
        initData();
        mPlayLocal = new PlayLocal();
        mAdapter = new StickyGridVideoAdapter(getActivity(), mGirdList, sticky_gridview);
        sticky_gridview.setAdapter(mAdapter);
    }

    private void initData() {
        Bundle bundle = getArguments();
        LeftLocalFileBean bean = (LeftLocalFileBean) bundle.getSerializable("bean");
        for (MyCamera camera : HiDataValue.CameraList) {
            if (camera.getUid().equals(bean.getUid())) {
                this.mMyCamera = camera;
                break;
            }
        }
        if (mMyCamera == null) {
            //说明摄像机被删除了 所以这里随便new 一个
            mMyCamera = new MyCamera(getActivity(), getString(R.string.title_camera_fragment), bean.getUid(), "admin", "admin");
            mMyCamera.isWallMounted = SharePreUtils.getBoolean(HiDataValue.CACHE, getActivity(), mMyCamera.getUid() + "isWallMounted");
            HiDataValue.DeleteCameraList.add(mMyCamera);
        }
        File folder = new File(bean.getFile().getAbsolutePath() + "/Download/");
        if (folder != null && folder.exists()) {
            File[] files = folder.listFiles();
            if (files.length > 0) {
                for (File file : files) {
                    long times = file.lastModified() / 1000;
                    GridItem gridItem = new GridItem(file.getAbsolutePath(), paserTimeToYM(times));
                    gridItem.setType(0);
                    //String[] strs=file.getName().split("\\.");
                    gridItem.setFileName(file.getName());
                    mGirdList.add(gridItem);
                }
            }
        }
        File folderRecord = new File(bean.getFile().getAbsolutePath() + "/VideoRecoding/");
        if (folderRecord != null && folderRecord.exists()) {
            File[] files = folderRecord.listFiles();
            if (files.length > 0) {
                for (File file : files) {
                    if (file.getName().equals("SnapShot")) {
                        continue;
                    }
                    long times = file.lastModified() / 1000;
                    GridItem gridItem = new GridItem(file.getAbsolutePath(), paserTimeToYM(times));
                    gridItem.setType(1);
                    //String[] strs=file.getName().split("\\.");
                    gridItem.setFileName(file.getName());
                    mGirdList.add(gridItem);
                }
            }
        }
        Collections.sort(mGirdList, new YMComparator());
        for (ListIterator<GridItem> it = mGirdList.listIterator(); it.hasNext(); ) {
            GridItem mGridItem = it.next();
            String ym = mGridItem.getTime();
            if (!sectionMap.containsKey(ym)) {
                mGridItem.setSection(section);
                sectionMap.put(ym, section);
                section++;
            } else {
                mGridItem.setSection(sectionMap.get(ym));
            }
        }
    }


    private String paserTimeToYM(long time) {
        TimeZone tz = TimeZone.getDefault();
        TimeZone.setDefault(tz);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date(time * 1000L));
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position < 0) return;
        mAdapter.playLocal = null;
        if (mAdapter.getDelMode() == 1) {
            CheckBox checkBox = (CheckBox) view.findViewById(R.id.grid_cb);
            checkBox.setChecked(checkBox.isChecked() ? false : true);
            if (checkBox.isChecked()) {
                mDeleteList.add(mGirdList.get(position));
            } else {
                mDeleteList.remove(mGirdList.get(position));
            }
            mAdapter.checks[position] = checkBox.isChecked();
        } else {
            GridItem gridItem = mGirdList.get(position);
            Bundle bundle = new Bundle();
            bundle.putString(FILE_PATH, gridItem.getPath());
            bundle.putString(HiDataValue.EXTRAS_KEY_UID, mMyCamera.getUid());

            String strat_time = converStr(gridItem);

            bundle.putString("strat_time", strat_time);
            Intent intent = new Intent();
            if (mMyCamera.isWallMounted) {
                intent.setClass(getActivity(), WallMountedPlayLocalActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                return;
            }
            if (mMyCamera.isFishEye()) {
                // 初始化鱼眼顶装和壁装的模式
                int num = SharePreUtils.getInt("mInstallMode", getActivity(), mMyCamera.getUid());
                mMyCamera.mInstallMode = num == -1 ? 0 : num;
                intent.setClass(getActivity(), FishEyePlaybackLocalActivity.class);
            } else {
                intent.setClass(getActivity(), PlaybackLocalActivity.class);
            }
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private String converStr(GridItem gridItem) {
        if (gridItem != null && !TextUtils.isEmpty(gridItem.getPath())) {
            String[] strings = gridItem.getPath().split("/");
            if (strings.length > 0) {
                String str = strings[strings.length - 1];
                String strTime = str.split("\\.")[0];
                strTime = strTime.replace("_", "");
                try {
                    Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(strTime);
                    return sdf.format(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return "";
                }
            }
        }
        return " ";
    }


    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        GridItem gridItem = mGirdList.get(position);
        Log.i("tedu", "----:" + gridItem.getPath());
        if (gridItem != null && !TextUtils.isEmpty(gridItem.getPath())) {
            String[] strings = gridItem.getPath().split("\\.");
            mFirstTime = 0;
            if (strings.length > 1) {
                if(mPlayLocal!=null){
                    mPlayLocal.registerPlayLocalStateListener(this);
                }
                if ("h264".equalsIgnoreCase(strings[1]) || "avi".equalsIgnoreCase(strings[1])) {
                    transDialogshow(gridItem);
                } else {
                    DumpDialogshow(gridItem);
                }
            }

        }
        return true;
    }

    protected void transDialogshow(final GridItem vi) {
        View customView = View.inflate(getActivity(), R.layout.dialog_transcord, null);
        final PopupWindow popupWindow = new PopupWindow(customView);
        ColorDrawable cd = new ColorDrawable(-000);
        popupWindow.setBackgroundDrawable(cd);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
        customView.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        customView.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (HiTools.isSDCardExist()) {
                    String[] strings = vi.getFileName().split("\\.");
                    File folderFiel = new File(HiDataValue.LOCAL_CONVERT_PATH + mMyCamera.getUid() + "/");
                    if (!folderFiel.exists()) {
                        folderFiel.mkdirs();
                    }
                    mConverFile = new File(folderFiel.getAbsolutePath() + "/" + strings[0] + ".mp4");
                    if (!mConverFile.exists()) {
                        try {
                            mConverFile.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        HiToast.showToast(getContext(), getContext().getString(R.string.file_alearly_convert));
                        return;
                    }
                    if (mPlayLocal != null) {
                        // 1: 本地文件  全路径
                        int b = mPlayLocal.Start2Mp4(vi.getPath(), mConverFile.getAbsolutePath());
                    }
                }
            }
        });
    }

    protected void DumpDialogshow(final GridItem vi) {
        final NiftyDialogBuilder dialog = NiftyDialogBuilder.getInstance(getContext());
        dialog.isCancelable(false).withTitle(getContext().getString(R.string.to_album)).withMessage(getContext().getString(R.string.tint_to_album)).withButton1Text(getContext().getString(R.string.cancel)).withButton2Text(getContext().getString(R.string.sure)).setButton1Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        }).setButton2Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                final File file = new File(HiDataValue.LOCAL_CONVERT_PATH + mMyCamera.getUid() + "/", vi.getFileName());
                if (HiTools.isSDCardExist() && file.exists()) {
                    HiToast.showToast(getContext(), getContext().getString(R.string.file_alearly_convert));
                    return;
                }
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                // 文件拷贝到convert文件夹
                if (file.isFile() && file.exists()) {
                    file.delete();
                }
                new Thread() {
                    public void run() {
                        copyFile(vi.getPath(), file.getAbsolutePath());
                        Message msg = Message.obtain();
                        msg.obj = file;
                        msg.what = 0X888;
                        mHandler.sendMessage(msg);
                    }
                }.start();
            }
        });
        dialog.show();
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { // 文件存在时
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0X888:
                    File file = (File) msg.obj;
                    if (file != null && file.exists() && file.isFile()) {
                        Uri localUri = Uri.fromFile(file);
                        Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
                        getContext().sendBroadcast(localIntent);
                        HiToast.showToast(getContext(), getContext().getString(R.string.success_to_album));
                    }
                    break;
                case PlayLocalFileCallback.LOCAL2MP4_STATE_OPEN:
                    showTransPupwindow(msg.arg1);
                    break;
                case PlayLocalFileCallback.LOCAL2MP4_STATE_ING:
                    int sub = msg.arg1;
                    int fileTime = msg.arg2;
                    int rate = (int) Math.round((double) sub / 1000 / fileTime * 100);
                    if (rate < 100) {
                        mTvTransRote.setText(rate + "%");
                    }
                    mSeekBarTrans.setProgress(sub);
                    break;
                case PlayLocalFileCallback.LOCAL2MP4_STATE_END:
                    mTvTransRote.setText("100%");
                    mTvCancel.setText(getContext().getString(R.string.finish));
                    break;
                case PlayLocalFileCallback.LOCAL2MP4_STATE_ERROR:
                    HiToast.showToast(getContext(), getContext().getString(R.string.data_parsing_error));
                    if (mConverFile != null && mConverFile.exists()) {
                        mConverFile.delete();
                    }
                    break;

            }

        }

        ;
    };

    private PopupWindow mPopupWindow;
    private TextView mTvCancel, mTvTransRote;
    private SeekBar mSeekBarTrans;

    private void showTransPupwindow(int filetime) {
        View customView = View.inflate(getContext(), R.layout.dialog_trans_pro, null);
        mPopupWindow = new PopupWindow(customView);
        ColorDrawable cd = new ColorDrawable(-000);
        mPopupWindow.setBackgroundDrawable(cd);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        mPopupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        mPopupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
        // 取消
        mTvCancel = (TextView) customView.findViewById(R.id.tv_cancel);
        mTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                if (getContext().getString(R.string.cancel).equals(mTvCancel.getText().toString())) {
                    mPlayLocal.Stop2Mp4();
                    // 删除文件
                    if (mConverFile.exists()) {
                        mConverFile.delete();
                    }
                }

            }
        });
        mTvTransRote = (TextView) customView.findViewById(R.id.rate_loading_trances);
        mSeekBarTrans = (SeekBar) customView.findViewById(R.id.sb_transd_video);
        mSeekBarTrans.setMax(filetime * 1000);
    }


    // 文件转码的回调

    /**
     * 视频宽，高，文件时长 ，文件播放进度，音频类型，播放状态
     */
    @Override
    public void callbackplaylocal(int width, int height, int filetime, long cursec, int audiotype, int state) {
        Message message = Message.obtain();
        switch (state) {
            case PlayLocalFileCallback.LOCAL2MP4_STATE_OPEN:
                message.what = PlayLocalFileCallback.LOCAL2MP4_STATE_OPEN;
                message.arg1 = filetime;
                mHandler.sendMessage(message);
                // showTransPupwindow();
                break;
            case PlayLocalFileCallback.LOCAL2MP4_STATE_ING:
                // if (cursec > 0) {
                if (mFirstTime == 0) {
                    mFirstTime = cursec;
                }
                int sub = (int) (cursec - mFirstTime);
                // if (sub > 0) {
                message.what = PlayLocalFileCallback.LOCAL2MP4_STATE_ING;
                message.arg1 = sub;
                message.arg2 = filetime;
                mHandler.sendMessage(message);
                // }
                // }
                break;
            case PlayLocalFileCallback.LOCAL2MP4_STATE_END:
                mPlayLocal.Stop2Mp4();
                mHandler.sendEmptyMessage(PlayLocalFileCallback.LOCAL2MP4_STATE_END);
                // 发通知图库更新文件显示
                Uri localUri = Uri.fromFile(mConverFile);
                Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
                getContext().sendBroadcast(localIntent);
                break;
            case PlayLocalFileCallback.LOCAL2MP4_STATE_ERROR:
                HiToast.showToast(getContext(), getString(R.string.data_parsing_error));
                break;
        }

    }
}
